# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1174': {  # dwc 支付方式和单笔限额qq钱包，微信h5,支付宝h5的单笔都是0---5000，京东h5的单笔是0---3000
        'API_KEY': 'E2544DF0656F4B24B746B28F7AE47297',
        'gateway': 'http://api.heinpay.com/orderpay/pay',
        'query_gateway': 'http://api.heinpay.com/api/query/querystatus',
    },
    '1782': {  # witch 支付宝3.8%（1---5000），qq1.8%（1---5000），京东2%（1---5000），快捷1%（1---2w）
        'API_KEY': 'D42FD21072064BD0B29FD53F91E7C9F7',
        'gateway': 'http://api.heinpay.com/orderpay/pay',
        'query_gateway': 'http://api.heinpay.com/api/query/querystatus',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=' + key
    _LOGGER.info("huiyinpay sign str: %s", s)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = 'amount={}merchantcode={}orderid={}paytime={}status={}key={}'.format(
        d['amount'], d['merchantcode'], d['orderid'], d['paytime'], d['status'], key
    )
    _LOGGER.info("huiyinpay sign notify str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("huiyinpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# ALIPAY	支付宝
# ALIPAYH5	支付宝H5
# WEIXIN	微信支付
# WEIXINH5	微信支付H5
# QQ	QQ扫码
# QQH5	QQ扫码H5
# JD	京东支付
# JDH5	京东支付H5
# BAIDU	百度钱包
# BAIDUH5	百度钱包H5
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'WEIXINH5'
    elif service == 'alipay':
        payType = 'ALIPAYH5'
    elif service == 'qq':
        payType = 'QQH5'
    elif service == 'jd':
        payType = 'JDH5'
    elif service == 'quick':
        payType = 'KUAIJIE'
    else:
        payType = 'BAIDUH5'
    return payType


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantcode', app_id),
        ('type', _get_pay_type(service)),
        ('amount', str(pay_amount)),
        ('orderid', str(pay.id)),
        ('notifyurl', '{}/pay/api/{}/huiyinpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("huiyinpay create: %s", parameter_dict)
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# 返回码	code	成功：success，失败：failed
# 描述	msg	返回码描述
{'code': 'success', 'msg': 'success'}


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("huiyinpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('huiyinpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['platformorderid']
    total_fee = float(data['amount'])
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 成功 = 0；失败 = 1
    if trade_status == '0':
        _LOGGER.info('huiyinpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantcode', app_id),
        ('orderid', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('huiyinpay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=10)
    _LOGGER.info('huiyinpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['amount'])
        trade_no = data['platformorderid']
        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 订单状态：处理中 = 1；已完成 = 2；已失败 = 4；
        if trade_status == '2':
            _LOGGER.info('huiyinpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
